﻿'Imports System.Configuration
'Imports Spring.Context
'Imports Spring.Data.Common
'Imports Spring.Data.Core
'Imports NHibernate.Event
'Imports Spring.Context.Support
'Imports Fgv.Framework.Seguranca.Servico
'Imports System.Web
'Imports System.Data

'Namespace Auditoria

'    ''' <summary>
'    ''' Classe Utilizada para tratar a aditoria em banco. 
'    ''' </summary>
'    ''' <remarks>Ela necessita de que o GerenteConfiguracao esteja com 
'    ''' o banco de dados devidamente ajustado.</remarks>
'    Public Class TratadorEventosAuditoria
'        Implements IPreUpdateEventListener, IPreInsertEventListener, IPreDeleteEventListener, IPostInsertEventListener

'        'Inherits AdoDaoSupport
'        Private Const semAutenticacao As Boolean = True

'        Private dbProvider As IDbProvider
'        Private adoTemplate As AdoTemplate
'        Private _autenticacaoServico As IAutenticacaoServico

'        Private usuario As String = ""
'        Private perfil As String = ""
'        Private _modulo As String = ""

'        ''' <summary>
'        ''' Propriedade de Modulo
'        ''' </summary>
'        ''' <value>String</value>
'        ''' <returns>String</returns>
'        ''' <remarks></remarks>
'        Public Property Modulo() As String
'            Get
'                If ConfigurationSettings.AppSettings("NomeModulo") IsNot Nothing Then
'                    _modulo = ConfigurationSettings.AppSettings("NomeModulo")
'                End If
'                Return _modulo
'            End Get
'            Set(ByVal value As String)
'                _modulo = value
'            End Set
'        End Property

'        Private IP As String = ""

'        ''' <summary>
'        ''' Propriedade de Provedor DB local
'        ''' </summary>
'        ''' <value>IDbProvider</value>
'        ''' <returns>IDbProvider</returns>
'        ''' <remarks></remarks>
'        Public Property LocalDbProvider() As IDbProvider
'            Get
'                If dbProvider Is Nothing Then
'                    dbProvider = GerenteConfiguracao.Instancia().ConBanco
'                End If
'                Return dbProvider
'            End Get
'            Set(ByVal value As IDbProvider)
'                dbProvider = value
'            End Set
'        End Property

'        Private Property LocalAdoTemplate() As AdoTemplate
'            Get
'                If adoTemplate Is Nothing Then
'                    adoTemplate = New AdoTemplate(LocalDbProvider())
'                End If
'                Return adoTemplate
'            End Get
'            Set(ByVal value As AdoTemplate)
'                adoTemplate = value
'            End Set
'        End Property

'        ''' <summary>
'        ''' Propriedade de autenticação de serviço
'        ''' </summary>
'        ''' <value>IAutenticacaoServico</value>
'        ''' <returns>IAutenticacaoServico</returns>
'        ''' <remarks></remarks>
'        Public Property AutenticacaoServico() As IAutenticacaoServico
'            Get
'                If _autenticacaoServico Is Nothing Then
'                    Dim ctx As IApplicationContext = ContextRegistry.GetContext()
'                    _autenticacaoServico = DirectCast(ctx("AutenticacaoServico"), IAutenticacaoServico)
'                End If
'                Return _autenticacaoServico
'            End Get
'            Set(ByVal value As IAutenticacaoServico)
'                _autenticacaoServico = value
'            End Set
'        End Property

'        Private Function PegarProximaOperacao() As Long
'            Dim res As Long = DirectCast(LocalAdoTemplate.ExecuteScalar(CommandType.Text, "execute GetNewSeqVal_SEQ_AUDITORIA"), Integer)
'            Return res
'            'GetNewSeqVal_SEQ_AUDITORIA()
'        End Function

'        Private Sub AcertaVariaveis()
'            'Verificando se o usuário está logado
'            Throw New NotImplementedException("Em refactory")
'            'If semAutenticacao Or AutenticacaoServico.UsuarioEstaAutenticado(HttpContext.Current) Then
'            '    'Acertando usuário e perfil 
'            '    usuario = AutenticacaoServico.ObtemNomeUsuarioAutenticado
'            '    If usuario Is Nothing Then
'            '        usuario = "SemAuth"
'            '    End If
'            '    'perfil =AutenticacaoServico.
'            '    IP = AutenticacaoServico.ObtemIPUsuarioAutenticado
'            'Else
'            '    Throw New Exception("Impossível prosseguir sem usuário! Favor entre em contato com o suporte.")
'            'End If

'        End Sub

'        Public Function OnPreUpdate(ByVal [event] As PreUpdateEvent) As Boolean Implements IPreUpdateEventListener.OnPreUpdate
'            AcertaVariaveis()

'            Dim oper As Long = PegarProximaOperacao()

'            Dim i As Integer = 0
'            Dim continuar As Boolean = False
'            For Each state In [event].State

'                If (IsNothing([event].OldState)) Then
'                    If Not (IsNothing(state) And IsNothing([event].OldState)) Then

'                        continuar = True

'                    End If
'                Else
'                    If IsNothing(state) Or IsNothing([event].OldState(i)) Then
'                        If Not (IsNothing(state) And IsNothing([event].OldState(i))) Then

'                            continuar = True

'                        End If
'                    Else
'                        If state.ToString <> [event].OldState(i).ToString Then

'                            continuar = True

'                        End If
'                    End If
'                End If


'                If continuar Then
'                    Dim name As String = [event].Persister.PropertyNames(i)

'                    Dim builder As IDbParametersBuilder
'                    builder = New DbParametersBuilder(LocalDbProvider)
'                    builder.Create().Name("DiaHora").Type(DbType.DateTime).Value(DateTime.Now)
'                    builder.Create().Name("Usuario").Type(DbType.String).Size(50).Value(usuario)
'                    builder.Create().Name("Perfil").Type(DbType.String).Size(50).Value(perfil)
'                    builder.Create().Name("Modulo").Type(DbType.String).Size(20).Value(Modulo)
'                    builder.Create().Name("Objeto").Type(DbType.String).Size(50).Value([event].Entity.GetType.Name)
'                    builder.Create().Name("Id").Type(DbType.Int64).Value([event].Id)
'                    builder.Create().Name("CampoAlterado").Type(DbType.String).Size(50).Value(name)
'                    'builder.Create().Name("ValorAnterior").Type(DbType.String).Size(1000).Value(prop.GetValue([event].OldState, Nothing).ToString)

'                    Dim vazio As Boolean = False
'                    If Not IsNothing([event].OldState) Then
'                        If Not IsNothing([event].OldState(i)) Then
'                            builder.Create().Name("ValorAnterior").Type(DbType.String).Size(1000).Value([event].OldState(i).ToString)
'                        Else
'                            vazio = True
'                        End If
'                    Else
'                        vazio = True
'                    End If

'                    If vazio Then
'                        builder.Create().Name("ValorAnterior").Type(DbType.String).Size(1000).Value(Nothing)
'                    End If

'                    builder.Create().Name("Operacao").Type(DbType.Int64).Value(oper)
'                    builder.Create().Name("IP").Type(DbType.String).Value(IP)

'                    LocalAdoTemplate.ExecuteNonQuery(CommandType.Text, "INSERT INTO Auditoria (Evento, DiaHora, Usuario, Perfil, Modulo, Objeto, Id, CampoAlterado, ValorAnterior, Operacao, IP) VALUES ('UPDATE', @DiaHora, @Usuario, @Perfil, @Modulo, @Objeto, @Id, @CampoAlterado, @ValorAnterior, @Operacao, @IP )", builder.GetParameters)

'                End If

'                i = i + 1
'            Next

'        End Function

'        Public Function OnPreInsert(ByVal [event] As PreInsertEvent) As Boolean Implements IPreInsertEventListener.OnPreInsert
'            AcertaVariaveis()
'            ' Por enquanto ainda não foi necessário usar. 
'        End Function

'        Public Function OnPreDelete(ByVal [event] As PreDeleteEvent) As Boolean Implements IPreDeleteEventListener.OnPreDelete
'            AcertaVariaveis()
'            Dim i As Integer = 0
'            Dim oper As Long = PegarProximaOperacao()
'            For Each state In [event].DeletedState
'                If state IsNot Nothing Then

'                    Dim name As String = [event].Persister.PropertyNames(i)

'                    Dim builder As IDbParametersBuilder
'                    builder = New DbParametersBuilder(LocalDbProvider)
'                    builder.Create().Name("DiaHora").Type(DbType.DateTime).Value(DateTime.Now)
'                    builder.Create().Name("Usuario").Type(DbType.String).Size(50).Value(usuario)
'                    builder.Create().Name("Perfil").Type(DbType.String).Size(50).Value(perfil)
'                    builder.Create().Name("Modulo").Type(DbType.String).Size(20).Value(Modulo)
'                    builder.Create().Name("Objeto").Type(DbType.String).Size(50).Value([event].Entity.GetType.Name)
'                    builder.Create().Name("Id").Type(DbType.Int64).Value([event].Id)
'                    builder.Create().Name("CampoAlterado").Type(DbType.String).Size(50).Value(name)
'                    'builder.Create().Name("ValorAnterior").Type(DbType.String).Size(1000).Value(prop.GetValue([event].OldState, Nothing).ToString)
'                    builder.Create().Name("ValorAnterior").Type(DbType.String).Size(1000).Value([event].DeletedState(i).ToString)
'                    builder.Create().Name("Operacao").Type(DbType.Int64).Value(oper)
'                    builder.Create().Name("IP").Type(DbType.String).Value(IP)

'                    LocalAdoTemplate.ExecuteNonQuery(CommandType.Text, "INSERT INTO Auditoria (Evento, DiaHora, Usuario, Perfil, Modulo, Objeto, Id, CampoAlterado, ValorAnterior, Operacao, IP) VALUES ('DELETE', @DiaHora, @Usuario, @Perfil, @Modulo, @Objeto, @Id, @CampoAlterado, @ValorAnterior, @Operacao, @IP )", builder.GetParameters)


'                End If

'                i = i + 1
'            Next
'        End Function

'        Public Sub OnPostInsert(ByVal [event] As NHibernate.Event.PostInsertEvent) Implements NHibernate.Event.IPostInsertEventListener.OnPostInsert
'            AcertaVariaveis()
'            Dim i As Long = PegarProximaOperacao()

'            Dim builder As IDbParametersBuilder
'            builder = New DbParametersBuilder(LocalDbProvider)
'            builder.Create().Name("DiaHora").Type(DbType.DateTime).Value(DateTime.Now)
'            builder.Create().Name("Usuario").Type(DbType.String).Size(50).Value(usuario)
'            builder.Create().Name("Perfil").Type(DbType.String).Size(50).Value(perfil)
'            builder.Create().Name("Modulo").Type(DbType.String).Size(20).Value(Modulo)
'            builder.Create().Name("Objeto").Type(DbType.String).Size(50).Value([event].Entity.GetType.Name)
'            builder.Create().Name("Id").Type(DbType.Int64).Value([event].Id)
'            builder.Create().Name("Operacao").Type(DbType.Int64).Value(i)
'            builder.Create().Name("IP").Type(DbType.String).Value(IP)

'            LocalAdoTemplate.ExecuteNonQuery(CommandType.Text, "INSERT INTO Auditoria (Evento, DiaHora, Usuario, Perfil, Modulo, Objeto, Id, Operacao, IP) VALUES ('INSERT', @DiaHora, @Usuario, @Perfil, @Modulo, @Objeto, @Id, @Operacao, @IP )", builder.GetParameters)

'        End Sub

'    End Class

'End Namespace
